package com.xjh.him.fragment.profile;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.xjh.him.R;
import com.xjh.him.activity.chat.ChatActivity;
import com.xjh.him.adapter.entity.Chat;
import com.xjh.him.adapter.entity.Session;
import com.xjh.him.common.Constant;
import com.xjh.him.core.BaseFragment;
import com.xjh.him.databinding.FragmentUserProfileBinding;
import com.xjh.him.dto.friend.FriendDTO;
import com.xjh.him.dto.friendapply.FriendApplyInfoDTO;
import com.xjh.him.dto.user.UserDTO;
import com.xjh.him.utils.MMKVUtils;
import com.xjh.him.utils.Utils;
import com.xjh.him.utils.XToastUtils;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.textview.supertextview.SuperTextView;
import com.xuexiang.xutil.app.ActivityUtils;

import org.xjh.tool.Checks;

import java.util.HashMap;
import java.util.Map;

@Page
public class UserProfileFragment extends BaseFragment<FragmentUserProfileBinding> {
    public static final int PAGE_CODE = 48953;
    public static final String KEY_IS_FRIEND = "isFriend";
    public static final String KEY_FRIEND_DTO = "friendDTO";

    private Boolean isFriend;
    private UserDTO userDTO;
    private FriendDTO friendDTO;

    @SuppressLint("StringFormatMatches")
    @Override
    protected void initViews() {
        isFriend = getArguments().getBoolean(KEY_IS_FRIEND);
        friendDTO = (FriendDTO) getArguments().getSerializable(KEY_FRIEND_DTO);
        String json = (String) MMKVUtils.get(Constant.MMKV_KEY_USER_DTO, "");
        if (!Checks.isEmpty(json)) {
            userDTO = JSON.parseObject(json, UserDTO.class);
        }

        if (isFriend != null && !isFriend) {
            binding.stvSendMsg.setVisibility(View.GONE);
            binding.stvApplyFriend.setVisibility(View.VISIBLE);
        }

        if (friendDTO != null) {
            ImageView imageView = binding.stvUserProfile.getLeftIconIV();
            Utils.setImageViewParams(imageView, 50, 50);
            Glide.with(this)
                    .load(friendDTO.getAvatarUrl())
                    .apply(Utils.getRoundedCornersRequestOptions(5))
                    .into(imageView);
            binding.stvUserProfile.setLeftTopString(friendDTO.getNickname());
            binding.stvUserProfile.setLeftBottomString(
                    binding.stvUserProfile.getLeftBottomString() + friendDTO.getSignature());
        }

        binding.stvSendMsg.setOnSuperTextViewClickListener(new SuperTextView.OnSuperTextViewClickListener() {
            @Override
            public void onClick(SuperTextView superTextView) {
                String json = (String) MMKVUtils.get(Constant.MMKV_KEY_USER_DTO, "");
                if (!Checks.isEmpty(json)) {
                    UserDTO userDTO = JSON.parseObject(json, UserDTO.class);
                    String queryAddUrl = Utils.getWebServerApiUrl(
                            requireActivity(),
                            String.format(getString(R.string.api_friend_group_query_add),
                                    userDTO.getId(), friendDTO.getId()));
                    SimpleCallBack<Long> queryGroupIdCB = new SimpleCallBack<Long>() {
                        @Override
                        public void onSuccess(Long groupId) throws Throwable {
                            Chat chat = new Chat();
                            chat.setGroupId(groupId);
                            chat.setGroupType(Session.GROUP_TYPE_SINGLE);
                            chat.setGroupName(friendDTO.getNickname());
                            chat.setGroupAvatar(friendDTO.getAvatarUrl());
                            Map<String, Object> map = new HashMap<>();
                            map.put(ChatActivity.KEY_CHAT, chat);
                            map.put(ChatActivity.KEY_FRIEND_DTO, friendDTO);
                            ActivityUtils.startActivityForResultWithBundle(
                                    requireActivity(),
                                    ChatActivity.class,
                                    PAGE_CODE,
                                    map
                            );
                            popToBack();
                        }

                        @Override
                        public void onError(ApiException e) {
                            XToastUtils.toast(e.getDisplayMessage());
                        }
                    };
                    Utils.doGet(queryAddUrl, queryGroupIdCB);
                }
            }
        });
        binding.stvApplyFriend.setOnSuperTextViewClickListener(new SuperTextView.OnSuperTextViewClickListener() {
            @Override
            public void onClick(SuperTextView superTextView) {
                FriendApplyInfoDTO applyInfoDTO = new FriendApplyInfoDTO();
                applyInfoDTO.setAppliedId(friendDTO.getId());
                applyInfoDTO.setApplyInfo("你好，我是" + userDTO.getNickname());
                String applyUrl = Utils.getSevServerApiUrl(requireActivity(), getString(R.string.api_friend_apply));
                SimpleCallBack<Boolean> applyCB = new SimpleCallBack<Boolean>() {
                    @Override
                    public void onSuccess(Boolean response) throws Throwable {
                        if (response) {
                            XToastUtils.toast("发送成功");
                            popToBack();
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        XToastUtils.toast(e.getDisplayMessage());
                    }
                };
                Utils.doPost(applyUrl, JSON.toJSONString(applyInfoDTO), applyCB);
            }
        });
    }

    @NonNull
    @Override
    protected FragmentUserProfileBinding viewBindingInflate(LayoutInflater inflater, ViewGroup container) {
        return FragmentUserProfileBinding.inflate(inflater, container, false);
    }

    @Override
    protected TitleBar initTitle() {
        return super.initTitle().setTitle("");
    }
}
